package javaweb.controller;

import javaweb.pojo.Result;
import javaweb.util.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {

    /*
     * 本地磁盘存储文件上传
     * */
    private static final String UPLOAD_DIR = "D:/code/JavaWeb/WebManagementProject/Jmu-Web-Management/src/main/resources/image/";
    /*
    * 本地磁盘保存文件
    * */
    /* @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        log.info("上传文件：{}", file);
        if (!file.isEmpty()) {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + extName;
            // 拼接完整的文件路径
            File targetFile = new File(UPLOAD_DIR + uniqueFileName);

            // 如果目标目录不存在，则创建它
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            // 保存文件
            file.transferTo(targetFile);
        }
        return Result.success();
    }*/

    @Autowired
    private AliyunOSSOperator ossOperator;

    /*
    * 阿里云OSS保存文件
    * */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        log.info("请求的参数file：{}" + file.getOriginalFilename());
        String url = ossOperator.upload(file.getBytes(), file.getOriginalFilename());
        log.info("返回的图片url: {}" + url);
        return Result.success(url);
    }

}
